#include "service.h"
#include "z_logger.h"
#include "z_memory.h"

static void *_service_start_routine(void *args) {
    aliot_service_t *service = args;

    service->handle = service->init(service->args);
    void *exit_code = service->start(service->handle);
    service->fini(&service->handle);

    return exit_code;
}

static void *_mqtt_start_routine(void *args) {
    aliot_service_t *service = args;

    void *exit_code = service->start(service->handle);
    service->fini(&service->handle);

    return exit_code;
}

int aliot_service_start(aliot_service_t *service) {
    int rc;

    log_info("start %s service", service->name);
    rc = pthread_create(&service->_state.pthread, NULL, _service_start_routine, service);
    if (rc < 0) {
        log_error("pthread_create = %d", rc);
    }

    return rc;
}

int aliot_mqtt_start(aliot_service_t *service) {
    int rc;

    log_info("start %s service", service->name);
    rc = pthread_create(&service->_state.pthread, NULL, _mqtt_start_routine, service);
    if (rc < 0) {
        log_error("pthread_create = %d", rc);
    }

    return rc;
}

int aliot_service_stop(aliot_service_t *service) {
    int rc;

    log_info("stop %s service", service->name);
    if (NULL != service->stop) {
        service->stop(&service->handle);
    }
    rc = pthread_join(service->_state.pthread, &service->_state.exit_code);
    if (rc < 0) {
        log_error("pthread_join = %d", rc);
    }

    return rc;
}